package com.example.flow.flow.model;


import com.example.flow.dao.model.FlowTask;
import com.example.flow.flow.FlowNodeInterceptor;
import com.example.flow.flow.core.Execution;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 线路
 *
 * @author tangaq
 * 2023/6/13
 */
public class TransitionModel {
    private NodeModel target;
    private String to;

    public TransitionModel() {
    }

    public TransitionModel(NodeModel target) {
        this.target = target;
        this.to = target.getName();
    }

    public void execute(Execution execution) {
        if (target instanceof TaskModel) {
            // 任务节点 创建task
            execution.getEngine().getTaskService().createTask((TaskModel) target, execution);
            // 执行前置拦截器
            doPreInterceptorList(execution);
        } else {
            // 其它节点 由目标节点执行
            target.execute(execution);
        }
    }

    public void doPreInterceptorList(Execution execution) {
        FlowTask task = execution.getTask();
        if (task == null) {
            return;
        }
        ProcessModel processModel = execution.getProcess().getModel();
        List<FlowNodeInterceptor> preInterceptorList = processModel.getNode(task.getTaskName()).getNextNode()
                .getTarget().getPreInterceptorList();
        if (CollectionUtils.isEmpty(preInterceptorList)) {
            return;
        }
        for (FlowNodeInterceptor interceptor : preInterceptorList) {
            // 执行校验
            interceptor.intercept(execution);
        }
    }

    public NodeModel getTarget() {
        return target;
    }

    public void setTarget(NodeModel target) {
        this.target = target;
        this.to = target.getName();
    }

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }
}
